// pages/userorders/userorders.js
const util = require('../../../../utils/util.js')
const Dialog = require('tdesign-miniprogram/dialog/index')
const App = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    selected: 0,
    list: ['待付款', '待发货', '待收货', '已完成'], //已取消:未发货的可取消，钱原路返回  --,'已完成','已取消'
    orderList: [],
    order_id: '',
    member_id: '',
    navStyle: [],
    noPayNum: 0, // 待付款数量
    noSendoutNum: 0, // 待发货数量
    noReceiveNum: 0, // 待收货数量
    completeNum: 0, // 已完成数量
    action: [],
    btnGroup: {
      showdes: '订单详情',
      delOrder: '删除订单',
      cancelOrder: '取消订单',
      goToPay: '立即支付',
      refundAfterSales: '拒绝退款|申请退款',
      viewLogistics: '查看物流',
      extendedRreceipt: '延长收货',
      confirmReceipt: '确认收货',
      viewEvaluate: '评价',
      afterSalesDetail: '售后详情|退款成功|退款中',
      anotherOrder: '再来一单'
    }
  },
  selected: function (e) {
    let that = this
    let index = e.currentTarget.dataset.index
    that.setData({
      selected: index
    })
    this.getData()
  },
  //返回上一页
  navigateBack: function () {
    wx.switchTab({
      url: 'pages/my/my'
    })
  },
  //获取全部订单信息--status:that.data.selected
  async getData() {
    const token = wx.getStorageSync('token')
    try {
      var that = this
      util
        .request(
          '/api/order/orderlist',
          {
            status: that.data.selected,
            token: token
          },
          'GET'
        )
        .then((res) => {
          this.cancelLoading()
          var datas = res.data.data.list
          if (datas && datas.length > 0) {
            // 不同状态展示不同按钮---@dou
            var actionLs = []
            // this.data.action = ['确认收货'];
            let bgcJchuAll = ['立即支付', '确认收货']
            let bgcJchuNone = ['订单详情', '取消订单', '申请退款']
            datas.forEach((v) => {
              actionLs = []
              v.action.forEach((vv) => {
                let useStyle = false
                if (bgcJchuAll.indexOf(vv) > -1) {
                  useStyle = 'bgcJchuAll'
                } else if (bgcJchuNone.indexOf(vv) > -1) {
                  useStyle = 'bgcJchuNone'
                }
                actionLs.push({
                  name: vv,
                  useMtd: this.checkMedthod(vv),
                  useStyle: useStyle
                })
              })
              v.action = actionLs
            })
            that.setData({
              orderList: datas
            })
            var noPayList = []
            var noSendoutList = []
            var noReceiveList = []
            var noAppraiseList = []
            that.data.orderList.forEach((item, index) => {
              switch (item.status) {
                case 2:
                  noPayList.push(item)
                  break
                case 3:
                  noSendoutList.push(item)
                  break
                case 4:
                  noReceiveList.push(item)
                  break
                case 5:
                  noAppraiseList.push(item)
                  break
                default:
                  break
              }
            })
            //  待支付数量
            // var noPayList=that.data.orderList.filter((item,index)=>{
            //   return item.status==2
            // })
            if (noPayList && noPayList.length > 0) {
              that.setData({
                noPayNum: noPayList.length
              })
            }
            if (noSendoutList && noSendoutList.length > 0) {
              that.setData({
                noSendoutNum: noSendoutList.length
              })
            }
            if (noReceiveList && noReceiveList.length > 0) {
              that.setData({
                noReceiveNum: noReceiveList.length
              })
            }
            if (noAppraiseList && noAppraiseList.length > 0) {
              that.setData({
                completeNum: noAppraiseList.length
              })
            }
          } else {
            that.setData({
              orderList: []
            })
          }
        })
    } catch (err) {
      console.log(err)
    }
  },
  //获取订单号，弹出付款页面
  async goToPay(e) {
    console.log(e, 'eee')
    var that = this
    const order_no = e.currentTarget.dataset.order_no
    try {
      wx.login({
        success: (res) => {
          const orderParams = {
            order_no,
            code: res.code
          }
          console.log(orderParams, 'orderParams==')
          //支付接口
          //const orderParams = { cart_ids, address_id, pay_type,order_price,token };
          //请求微信支付
          util.request('/api/order/wxpayV2', orderParams, 'POST').then((res) => {
            var data = res.data.data
            console.log(data)
            if (data.pay_state == 1) {
              console.log('支付失败')
              that.setData({
                goPay: 2
              })
              //  that.onLoad()
              wx.navigateTo({
                url: '/pages/statepages/statepages?pay_state=1'
              })
              return
            } else {
              let { signData, paySig, signature } = data.pay_params
              wx.requestCommonPayment({
                mode: 'retail_pay_goods',
                signData: signData,
                paySig: paySig,
                signature: signature,
                success: function (res) {
                  if (res.errMsg == 'requestCommonPayment:ok') {
                    that.setData({
                      goPay: 2
                    })
                    //   this.getData();
                    // 支付成功跳转页面

                    wx.navigateTo({
                      url: '/pages/statepages/statepages?pay_state=0'
                    })
                  }
                },
                fail: function (res) {
                  wx.showToast({
                    title: '支付失败'
                  })
                  wx.navigateTo({
                    url: '/pages/statepages/statepages?pay_state=1'
                  })
                }
              })
            }
          })
        }
      })

      // that.setData({
      //   // goPay: 2
      // });
      // wx.showToast({ title: "支付成功" });
      //手动删除处理购物车已有数据
      //页面跳转
      // wx.navigateTo({ url: "/pages/order/index" });
    } catch (error) {
      wx.showToast({
        title: '支付失败'
      })
      console.log(error)
    }
  },
  //取消订单
  async cancelOrder(e) {
    const dialogConfig = {
      context: this,
      title: '',
      closeOnOverlayClick: true,
      content: '确认要取消当前订单吗？',
      confirmBtn: '确定',
      cancelBtn: '取消'
    }
    Dialog.default
      .confirm(dialogConfig)
      .then(() => {
        console.log('点击了确定')
        var order_id = e.currentTarget.dataset.order_id
        try {
          //判断缓存是否存在token
          const token = wx.getStorageSync('token')
          //不存在token时
          if (!token) {
            //不存在token值--重新登录
            wx.navigateTo({
              url: '/pages/auth/index'
            })
            return
          }
          //请求头参数
          const header = {
            Authorization: token
          }
          // const pay_type = "WechatPay"
          const orderParams = {
            order_id,
            token
          }
          util.request('/api/order/cancelOrder', orderParams, 'POST').then((res) => {
            if (res.data.code == 0) {
              this.getData()
              wx.showToast({
                title: '取消订单成功',
                icon: 'success',
                duration: 4000 //持续的时间
              })
            } else {
              wx.showToast({
                title: '取消订单失败'
              })
            }
          })
        } catch (err) {
          wx.showToast({
            title: '取消订单接口请求失败'
          })
          console.log('取消订单错误：' + err)
        }
      })
      .catch(() => console.log('点击了取消'))
  },
  //修改地址
  async changeAddress(e) {
    var that = this
    var order_no = e.currentTarget.dataset.order_no
    wx.showToast({
      title: '修改地址接口未写'
    })
  },
  //查看物流
  async viewLogistics(e) {
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    wx.showToast({
      title: '查看物流接口未写'
    })
  },
  //查看评价
  async viewEvaluate(e) {
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    wx.navigateTo({
      url: '/modules/userModule/pages/userordersinfo/userordersinfo?selected=4&order_id=' + order_id
    })
  },
  //提醒发货
  async anotherOrder(e) {
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    wx.showToast({
      title: '提醒发货成功'
    })
  },
  //退款/售后
  async refundAfterSales(e) {
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    wx.navigateTo({
      url: '/pages/userorderrefundType/userorderrefundType?order_id=' + order_id
    })
  },
  //提醒发货
  async remindDeliverGoods(e) {
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    wx.showToast({
      title: '提醒发货成功'
    })
  },
  //延长收货
  async extendedRreceipt(e) {
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    try {
      //判断缓存是否存在token
      const token = wx.getStorageSync('token')
      //不存在token时
      if (!token) {
        //不存在token值--重新登录
        wx.navigateTo({
          url: '/pages/auth/index'
        })
        return
      }
      //请求头参数
      const header = {
        Authorization: token
      }
      const orderParams = {
        order_id,
        token
      }
      util.request('/api/order/extendOrder', orderParams, 'POST').then((res) => {
        if (res.data.code == 0) {
          wx.showToast({
            title: '延长收货成功',
            icon: 'success', //图标，支持"success"、"loading"
            //image: '/images/tan.png',//自定义图标的本地路径，image 的优先级高于 icon
            duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
            mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
            success: function () {}
          })
          this.getData()
        } else {
          wx.showToast({
            title: '延长收货失败',
            icon: 'error', //图标，支持"success"、"loading"
            //image: '/images/tan.png',//自定义图标的本地路径，image 的优先级高于 icon
            duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
            mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
            success: function () {}
          })
        }
      })
    } catch (err) {
      wx.showToast({
        title: '延长收货时间接口请求失败'
      })
      console.log('延长收货时间错误：' + err)
    }
  },
  //确认收货
  async confirmReceipt(e) {
    var that = this
    const dialogConfig = {
      context: this,
      title: '',
      closeOnOverlayClick: true,
      content: '您确定收到商品了吗？',
      confirmBtn: '确定',
      cancelBtn: '取消'
    }
    Dialog.default
      .confirm(dialogConfig)
      .then(() => {
        var order_id = e.currentTarget.dataset.order_id
        try {
          //判断缓存是否存在token
          const token = wx.getStorageSync('token')
          //不存在token时
          if (!token) {
            //不存在token值--重新登录
            wx.navigateTo({
              url: '/pages/auth/index'
            })
            return
          }
          //请求头参数
          const header = {
            Authorization: token
          }
          const orderParams = {
            order_id,
            token
          }
          util.request('/api/order/confirmReceipt', orderParams, 'POST').then((res) => {
            if (res.data.code == 0) {
              wx.showToast({
                title: '确认收货成功',
                icon: 'success', //图标，支持"success"、"loading"
                //image: '/images/tan.png',//自定义图标的本地路径，image 的优先级高于 icon
                duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
                mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
                success: function () {}
              })
              this.getData()
            } else {
              wx.showToast({
                title: '确认收货失败',
                icon: 'error', //图标，支持"success"、"loading"
                //image: '/images/tan.png',//自定义图标的本地路径，image 的优先级高于 icon
                duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
                mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false
                success: function () {}
              })
            }
          })
        } catch (err) {
          wx.showToast({
            title: '确认收货时间接口请求失败'
          })
          console.log('确认收货时间错误：' + err)
        }
      })
      .catch(() => {
        // 点击取消
      })
  },
  //删除订单
  async delOrder(e) {
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    try {
      //判断缓存是否存在token
      const token = wx.getStorageSync('token')
      //不存在token时
      if (!token) {
        //不存在token值--重新登录
        wx.navigateTo({
          url: '/pages/auth/index'
        })
        return
      }
      //请求头参数
      const header = {
        Authorization: token
      }
      const orderParams = {
        order_id,
        token
      }
      util.request('/api/order/removeOrder', orderParams, 'POST').then((res) => {
        if (res.data.code == 0) {
          wx.showToast({
            title: '删除订单成功'
          })
          // that.onLoad()
          this.getData()
        } else {
          wx.showToast({
            title: '删除订单失败'
          })
        }
      })
    } catch (err) {
      wx.showToast({
        title: '删除订单接口请求失败'
      })
      console.log('删除订单错误：' + err)
    }
  },
  //申请发票
  async applyInvoice(e) {
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    wx.showToast({
      title: '申请发票接口未写'
    })
  },
  //查看详情
  async showdes(e) {
    var order_id = e.currentTarget.dataset.order_id
    // console.log(order_id)
    wx.navigateTo({
      url: '/modules/userModule/pages/userordersinfo/userordersinfo?order_id=' + order_id + '&selected=' + this.data.selected
    })
  },
  // 查看售后详情
  async afterSalesDetail(e) {
    var order_id = e.currentTarget.dataset.order_id
    wx.navigateTo({
      url: '/pages/userorderrefund/userorderrefund?order_id=' + order_id + '&selected=10'
    })
  },
  // 展示loading 加载效果
  showLoading: function () {
    wx.showToast({
      title: '加载中',
      icon: 'loading'
    })
  },
  // 关闭loading加载
  cancelLoading: function () {
    wx.hideToast()
  },
  changeData: function () {
    this.getData()
    console.log('刷新')
  },
  // 通过操作获取按钮操作方法
  checkMedthod(e) {
    //获取键值
    let useMedthod = false
    let btnGroup = this.data.btnGroup
    Object.keys(btnGroup).forEach((k) => {
      if (useMedthod) return
      if (btnGroup[k].indexOf(e) > -1) {
        useMedthod = k
      }
    })
    return useMedthod
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.setData({
    //   action:actionLs,
    // });

    if (util.isLogin() == true) {
      this.showLoading()
      this.setData({
        navStyle: App.globalData,
        selected: options.status ? options.status : 0
      })
      this.getData()
      // 返回上一页并刷新上一页
      var pages = getCurrentPages()
      if (pages.length > 1) {
        //上一个页面实例对象
        var prePage = pages[pages.length - 2]
        //关键在这里,这里面是触发上个界面
        prePage.changeData()
      }
    } else {
      util.isLogin()
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (util.isLogin() == true) {
      this.getData()
    } else {
      util.isLogin()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
})
